package com.iocup.keybastion.sso.core;


import com.iocup.keybastion.configuration.SecurityProperties;
import com.iocup.keybastion.context.WebContextHolder;
import com.iocup.keybastion.core.impl.DefaultHttpActionAdapter;
import com.iocup.keybastion.exception.CredentialsEmptyException;
import com.iocup.keybastion.sso.common.SsoRouterNotFoundException;
import com.pine.sunflower.core.model.CommonErrorCode;
import com.pine.sunflower.core.model.HttpStatus;
import com.pine.sunflower.core.model.Result;
import com.pine.sunflower.core.utils.JsonUtils;
import lombok.Setter;

/**
 * @author xyjxust
 * @create 2022/3/4 10:57
 **/
public class DefaultSsoHttpActionAdapter extends DefaultHttpActionAdapter {

    @Setter
    private SsoAuthFunction ssoAuthFunction;
    @Setter
    private SecurityProperties securityProperties;

    @Override
    public Object adapt(Exception e, WebContextHolder webContextHolder) {
        if (e == null) {
            return null;
        }
        if (securityProperties.isNoLogin2Redirect()) {
            if (e instanceof CredentialsEmptyException) {
                ssoAuthFunction.handle(webContextHolder);
                return null;
            }
        }
        if(e instanceof SsoRouterNotFoundException){
            webContextHolder.setResponseStatus(HttpStatus.REQUEST_NOT_FOUND.getCode());
            webContextHolder.setResponseContentType("application/json;charset=utf-8");
            /**
             * @todo 还未进行错误码处理
             */
            webContextHolder.responseOutput(JsonUtils.toString(Result.error(CommonErrorCode.REQUEST_ERROR.getCode(),e.getMessage())));
            return null;
        }
        return super.adapt(e, webContextHolder);

    }
}
